import React, { useState } from 'react';
import { Empty, Tabs, Card, Radio, Space, Alert } from 'antd';
import { 
  ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, 
  ResponsiveContainer, PieChart, Pie, Cell, BarChart, Bar,
  Legend, LabelList
} from 'recharts';
import { RetrievalResult } from '../../services/RetrievalService';

const { TabPane } = Tabs;

interface RetrievalVisualizerProps {
  searchResults: RetrievalResult[];
  query: string;
  previousResults?: RetrievalResult[];
}

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884d8', '#82ca9d'];

const RetrievalVisualizer: React.FC<RetrievalVisualizerProps> = ({ 
  searchResults, 
  query,
  previousResults = []
}) => {
  const [graphMode, setGraphMode] = useState<'current' | 'comparison'>('current');

  if (!searchResults.length) {
    return <Empty description="执行检索后显示结果可视化" />;
  }

  // 向量空间投影（假设的2D投影）
  const generateVectorProjection = (results: RetrievalResult[]) => {
    return results.map((result, index) => ({
      x: Math.random() * 100,  // 实际应该使用t-SNE或UMAP降维
      y: Math.random() * 100,
      title: result.title,
      score: result.score,
      id: result.id,
      rank: index + 1,
      type: result.metadata?.resultType || 'vector'
    }));
  };

  const scatterData = generateVectorProjection(searchResults);
  const previousScatterData = previousResults.length 
    ? generateVectorProjection(previousResults) 
    : [];

  // 来源分布数据
  const getSourceDistribution = (results: RetrievalResult[]) => {
    const sourceMap: Record<string, number> = {};
    
    results.forEach(result => {
      const domain = new URL(result.source).hostname;
      sourceMap[domain] = (sourceMap[domain] || 0) + 1;
    });
    
    return Object.entries(sourceMap).map(([name, value]) => ({ name, value }));
  };

  const sourceData = getSourceDistribution(searchResults);

  // 分数分布
  const getScoreDistribution = (results: RetrievalResult[]) => {
    const scoreRanges = [
      { name: '高 (>0.8)', range: '0.8-1.0', value: 0 },
      { name: '中 (0.6-0.8)', range: '0.6-0.8', value: 0 },
      { name: '低 (0.4-0.6)', range: '0.4-0.6', value: 0 },
      { name: '很低 (<0.4)', range: '0-0.4', value: 0 }
    ];
    
    results.forEach(result => {
      if (result.score > 0.8) {
        scoreRanges[0].value += 1;
      } else if (result.score > 0.6) {
        scoreRanges[1].value += 1;
      } else if (result.score > 0.4) {
        scoreRanges[2].value += 1;
      } else {
        scoreRanges[3].value += 1;
      }
    });
    
    return scoreRanges;
  };

  const scoreData = getScoreDistribution(searchResults);
  
  // 类型分布
  const getTypeDistribution = (results: RetrievalResult[]) => {
    const typeCounts: Record<string, number> = {
      vector: 0,
      keyword: 0,
      hybrid: 0
    };
    
    results.forEach(result => {
      const type = result.metadata?.resultType || 'vector';
      typeCounts[type] = (typeCounts[type] || 0) + 1;
    });
    
    return Object.entries(typeCounts)
      .filter(([_, value]) => value > 0)
      .map(([name, value]) => ({ 
        name: name === 'vector' ? '向量' : name === 'keyword' ? '关键词' : '混合', 
        value 
      }));
  };

  const typeData = getTypeDistribution(searchResults);
  
  // 分数比较 (当前与之前的结果比较)
  const getScoreComparison = () => {
    if (!previousResults.length) return [];
    
    // 找到两个结果集中都存在的文档
    const commonDocs: any[] = [];
    
    searchResults.forEach((current, currentIndex) => {
      const prevIndex = previousResults.findIndex(prev => prev.id === current.id);
      if (prevIndex !== -1) {
        commonDocs.push({
          id: current.id,
          title: current.title.length > 20 
            ? current.title.substring(0, 20) + '...' 
            : current.title,
          currentScore: current.score,
          previousScore: previousResults[prevIndex].score,
          currentRank: currentIndex + 1,
          previousRank: prevIndex + 1
        });
      }
    });
    
    return commonDocs;
  };

  const comparisonData = getScoreComparison();
  
  return (
    <div className="retrieval-visualizer">
      {previousResults.length > 0 && (
        <div style={{ marginBottom: 16 }}>
          <Radio.Group 
            value={graphMode} 
            onChange={e => setGraphMode(e.target.value)}
            optionType="button" 
            buttonStyle="solid"
          >
            <Radio.Button value="current">当前结果</Radio.Button>
            <Radio.Button value="comparison">结果比较</Radio.Button>
          </Radio.Group>
        </div>
      )}
      
      {graphMode === 'comparison' && previousResults.length > 0 ? (
        <div>
          <Alert 
            message="结果比较模式" 
            description="对比展示两次检索的结果差异，看看参数调整带来的影响。" 
            type="info" 
            showIcon 
            style={{ marginBottom: 16 }}
          />
          
          <Card title="分数变化" style={{ marginBottom: 16 }}>
            <ResponsiveContainer width="100%" height={400}>
              <BarChart
                data={comparisonData}
                layout="vertical"
                margin={{ top: 20, right: 30, left: 100, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis type="number" domain={[0, 1]} />
                <YAxis 
                  dataKey="title" 
                  type="category" 
                  width={100}
                />
                <Tooltip />
                <Legend />
                <Bar dataKey="previousScore" name="先前分数" fill="#8884d8" />
                <Bar dataKey="currentScore" name="当前分数" fill="#82ca9d" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
          
          <Card title="排名变化">
            <ResponsiveContainer width="100%" height={400}>
              <BarChart
                data={comparisonData}
                layout="vertical"
                margin={{ top: 20, right: 30, left: 100, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis type="number" domain={[0, Math.max(
                  ...comparisonData.map(d => Math.max(d.previousRank, d.currentRank))
                )]} reversed />
                <YAxis 
                  dataKey="title" 
                  type="category" 
                  width={100}
                />
                <Tooltip />
                <Legend />
                <Bar dataKey="previousRank" name="先前排名" fill="#ffbb28" />
                <Bar dataKey="currentRank" name="当前排名" fill="#ff8042" />
              </BarChart>
            </ResponsiveContainer>
          </Card>
        </div>
      ) : (
        <Tabs defaultActiveKey="vector">
          <TabPane tab="向量分布" key="vector">
            <Card>
              <ResponsiveContainer width="100%" height={400}>
                <ScatterChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
                  <CartesianGrid />
                  <XAxis type="number" dataKey="x" name="降维坐标X" />
                  <YAxis type="number" dataKey="y" name="降维坐标Y" />
                  <Tooltip 
                    cursor={{ strokeDasharray: '3 3' }}
                    content={({ payload }) => {
                      if (payload && payload.length) {
                        const data = payload[0].payload;
                        return (
                          <div style={{ backgroundColor: 'white', padding: 10, border: '1px solid #ccc' }}>
                            <p>{data.title}</p>
                            <p>排名: {data.rank}</p>
                            <p>相关度: {(data.score * 100).toFixed(2)}%</p>
                            <p>类型: {data.type === 'vector' ? '向量' : 
                                     data.type === 'keyword' ? '关键词' : '混合'}</p>
                          </div>
                        );
                      }
                      return null;
                    }}
                  />
                  <Scatter 
                    name="文档向量" 
                    data={scatterData} 
                    fill="#8884d8"
                    shape="circle"
                  />
                </ScatterChart>
              </ResponsiveContainer>
            </Card>
          </TabPane>
          
          <TabPane tab="来源分布" key="source">
            <Card>
              <ResponsiveContainer width="100%" height={400}>
                <PieChart>
                  <Pie
                    data={sourceData}
                    cx="50%"
                    cy="50%"
                    labelLine={true}
                    outerRadius={150}
                    fill="#8884d8"
                    dataKey="value"
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  >
                    {sourceData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </TabPane>
          
          <TabPane tab="分数分布" key="score">
            <Card>
              <ResponsiveContainer width="100%" height={400}>
                <PieChart>
                  <Pie
                    data={scoreData}
                    cx="50%"
                    cy="50%"
                    labelLine={true}
                    outerRadius={150}
                    fill="#8884d8"
                    dataKey="value"
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  >
                    {scoreData.map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={['#52c41a', '#1890ff', '#faad14', '#f5222d'][index]} />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </TabPane>
          
          <TabPane tab="结果类型" key="type">
            <Card>
              <ResponsiveContainer width="100%" height={400}>
                <PieChart>
                  <Pie
                    data={typeData}
                    cx="50%"
                    cy="50%"
                    labelLine={true}
                    outerRadius={150}
                    fill="#8884d8"
                    dataKey="value"
                    label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                  >
                    {typeData.map((entry, index) => (
                      <Cell 
                        key={`cell-${index}`} 
                        fill={
                          entry.name === '向量' ? '#1890ff' : 
                          entry.name === '关键词' ? '#faad14' : 
                          '#722ed1'
                        } 
                      />
                    ))}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            </Card>
          </TabPane>
        </Tabs>
      )}
    </div>
  );
};

export default RetrievalVisualizer; 